package Core;
/*
 *  J2Egn version 2.6.28
 *  Author: Van Tan Tai 2010-2011
 *  Interface MIDCan
 */
import javax.microedition.lcdui.Canvas;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Graphics;
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;

import Const.GConfig;

public class GMain extends MIDlet {

	public GCanvas m_canvas;
	public static GMain gMidlet = null;
	public GMain(){ gMidlet = this; m_canvas = new GCanvas(); }
	protected void startApp() throws MIDletStateChangeException
	{ Display.getDisplay(this).setCurrent(m_canvas); }
	protected void pauseApp() {	}
	public void destroyApp(boolean arg0){
		System.out.println("+ DESTROY APP!");
		try{ m_canvas.app.destroy(); this.notifyDestroyed(); }
		catch (Exception e){}
	}

	class GCanvas extends Canvas implements Runnable {
		
		private GLives app = new GLives();
		private Thread mainThread = null;
		private boolean bRun = false;
		private long lTime;
		
		public GCanvas() {
			System.out.println("+ INIT APP");
			this.setFullScreenMode(true);
			app.init(hasPointerEvents(), System.getProperty("microedition.platform"), getKeyCode(Canvas.FIRE), GMain.gMidlet.getAppProperty("MIDlet-Version"), isQwertyKeyPad());
			app.init(getWidth(), getHeight());
		}
		
		private boolean isQwertyKeyPad() {
			try {
				for (int i = 65; i < (65 + 26); i++) getKeyName(i);
				return true;
			} catch (Exception e) {
				return false;
			}
		}
		
		protected void sizeChanged(int width, int height){
			System.out.println("+ SIZE CHANGE");
			app.onResize(width, height);
		}
		
		protected void paint(Graphics g) {
			app.paint(g);
		}

		public void keyPressed(int keyCode) {
			app.onkeyDown(keyCode);
		}
		public void keyReleased(int keyCode) {
			app.onkeyUp(keyCode);
		}
//		public void keyRepeated(int keyCode) {
//			app.keyRepeated(KEY.getKey(keyCode, KEY.PRESS));
//		}
		
		protected void pointerDragged(int x, int y) {
			app.touchDrag(x, y);
		}
		protected void pointerPressed(int x, int y) {
			app.touchDown(x, y);
		}
		protected void pointerReleased(int x, int y) {
			app.touchUp(x, y);
		}

		protected void hideNotify() {
			System.out.println("+ APP PAUSE");
			app.pause();
			if(GConfig.isDestroyThread){
				mainThread = null;
				bRun = false;
			}
			System.gc();
		}

		protected void showNotify(){
			if (mainThread == null) {
				bRun = true;
				mainThread = new Thread(this);
				mainThread.start();
			}
			app.resume();
		}
		
		public void run() {
			while (bRun) {
				lTime = System.currentTimeMillis();
				
//				app.iframe++;
//				if(app.iframe >= Integer.MAX_VALUE )
//					app.iframe = 0;
				
				app.update();
				repaint();
				serviceRepaints();
				
	            try { Thread.sleep( 43 - (System.currentTimeMillis() - lTime) );
	            } catch (Exception e){}
			}
		}
	}
}
